package com.youlu.campus.admin.vote.service;

import com.youlu.campus.admin.vote.dto.OrgTypeSaveDTO;
import com.youlu.campus.admin.vote.dto.OrgTypeSearchDTO;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.vote.OrganizationType;
import com.youlu.campus.service.course.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author : [dengbo]
 * @className : OrgTypeService
 * @description : [组织类型服务]
 * @createTime : [2022/7/4 10:06]
 */
@Service
@Slf4j
public class OrgTypeService {
    @Autowired
    private MongoTemplate mongoTemplate;

    public boolean save(OrgTypeSaveDTO saveDTO) {
        OrganizationType organizationType = null;
        if (StringUtils.isNotBlank(saveDTO.getId())) {
            //修改
            organizationType = mongoTemplate.findOne(Query.query(Criteria.where("id").is(saveDTO.getId())), OrganizationType.class);
            if (organizationType == null) {
                throw new BusinessException("组织类型Id不存在");
            }
            organizationType.setOrgType(saveDTO.getOrgType());
            organizationType.setName(saveDTO.getName());
            mongoTemplate.save(organizationType);
        } else {
            organizationType = new OrganizationType();
            organizationType.setName(saveDTO.getName());
            organizationType.setOrgType(saveDTO.getOrgType());
            mongoTemplate.save(organizationType);
        }
        return true;
    }

    public Page<OrganizationType> list(OrgTypeSearchDTO dto) {
        QueryWrapper query = new QueryWrapper();
        if (StringUtils.isNotBlank(dto.getName())) {
            query.like("name", dto.getName());
        }
        query.addCriteria(Criteria.where("deleted").ne(true));
        long count = mongoTemplate.count(query, OrganizationType.class);
        query.with(Sort.by(Sort.Order.desc("createdTime")));
        PageRequest pageRequest = PageRequest.of(dto.getPage() - 1, dto.getPageSize());
        List<OrganizationType> data = mongoTemplate.find(query.with(pageRequest), OrganizationType.class);
        return PageableExecutionUtils.getPage(data, pageRequest, () -> count);
    }
}
